<script lang="ts">
  import type { Folder, Editor } from "$lib/ebm";
  import { actixGraphqlEndpoint, activeFolderId } from "$lib/js/stores";
  import { onDestroy } from "svelte";

  import { request, gql } from "graphql-request";
  import FolderNode from "./FolderNode.svelte";

  import { tooltip } from "$lib/js/tooltip";
  import { useMutation, useQueryClient } from "@sveltestack/svelte-query";

  export let expanded = false;
  export let folder: Folder;

  const queryClient = useQueryClient();

  let endpoint = $actixGraphqlEndpoint;
  const openEditorMutation = useMutation<
    Editor,
    { message: string },
    {
      id_: string;
      title_: string;
    }
  >(
    async ({ id_, title_ }) => {
      const { editor } = await request(
        endpoint,
        gql`
          mutation ($id: ID!, $title: String!) {
            editor: openEditor(input: { id: $id, title: $title }) {
              id
              snapshotAt
              title
              createdAt
              updatedAt
              status
              from
            }
          }
        `,
        {
          id: id_,
          title: title_,
        }
      );
      return editor;
    },
    {
      onSuccess: () => {
        queryClient.invalidateQueries("editors_query");
      },
    }
  );

  function openEditor() {
    $openEditorMutation.mutate({
      id_: folder.id,
      title_: folder.folderName,
    });
    console.log(
      "double click to open editor for folder={}, id={}",
      folder.folderName,
      folder.id
    );
  }

  const handleFolderClick = (id) => () => {
    expanded = !expanded;
    alert("handleFolderClick activeEdgeId=" + $activeFolderId);
  };

  const handleFolderAddClick = () => () => {
    alert(
      "handleFolderAddClick add sub folder to activeFolderId=" + $activeFolderId
    );
  };
</script>

<header
  class="py-1 px-1 bg-gray-700 
      bg-chevron-right bg-no-repeat pl-8 flex flex-row text-white"
>
  <span class="flex-1 text-gray-200 text-left truncate "> 资源管理器 </span>
  <div class="flex flex-row">
    <button
      class="bg-folder-add bg-no-repeat pl-8"
      use:tooltip={{ theme: "light" }}
      title="Folder Add"
      on:click={handleFolderAddClick()}
    />
  </div>
</header>

<main class="flex-1 overflow-y-auto p-1 w-full flex flex-col">
  <FolderNode {folder} {expanded} />
</main>
